package io.nads.controller;

import io.nads.constant.FrontendConstant;
import io.nads.dto.Result;
import io.nads.entity.User;
import io.nads.service.IUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
@Tag(name="用户接口",description = "用户的增删改查")
public class UserController {

    private final IUserService userService;

    /**
     * 获取当前登录的用户的信息
     * @param request
     * @return result.data = User
     */
    @GetMapping
    public Result getMySelf(HttpServletRequest request) {
        log.info("用户获取个人信息");
        // 从redis获取用户名
        String token = request.getHeader(FrontendConstant.AUTHORIZATION_HEADER_KEY);
        return userService.getUserByToken(token);
    }

    /**
     * 发送验证码
     * @param email
     * @return
     */
    @PostMapping("/sendCode")
    public Result sendCode(@RequestBody String email) {
        log.info("用户获取验证码 {}", email);
        return userService.sendCode(email);
    }


    /**
     * 注册用户
     * @param user
     * @return
     */
    @PostMapping("/register")
    public Result register(@RequestBody User user) {
        log.info("用户注册 {}", user);
        return userService.register(user);
    }

    /**
     * 用户登录
     * @param user
     * @return
     */
    @PostMapping("/login")
    @Operation(summary = "登录",description = "用户登录")
    public Result login(@RequestBody User user) {
        log.info("用户登录 {}", user);
        return userService.login(user);
    }

    /**
     * 用户退出登录
     */
    @GetMapping("/logout")
    public Result logout(HttpServletRequest request) {
        String token = request.getHeader(FrontendConstant.AUTHORIZATION_HEADER_KEY);
        return userService.logout(token);
    }
}
